<template>
  <div class="setmenu-container" v-loading="loading" element-loading-text="数据加载中...">
    <el-card class="search-box">
      <el-input
        v-model="searchKey"
        placeholder="输入套餐名称搜索"
        style="width: 300px"
        clearable
        @input="handleSearch"
      />
      <el-button type="success" @click="handleCreate" style="margin-left: 15px">
        新增套餐
      </el-button>
    </el-card>

    <div class="setmenu-list">
      <div
        v-for="item in tableData"
        :key="item.id"
        class="setmenu-card"
      >
        <div class="header">
          <h3>{{ item.name }}</h3>
          <el-tag :type="item.list === 1 ? 'success' : 'danger'">
            {{ item.list === 1 ? '已上架' : '已下架' }}
          </el-tag>
        </div>

        <div class="product-previews">
          <div
            v-for="product in item.products"
            :key="product.id"
            class="preview-item"
          >
            <img :src="product.img || '/default-product.png'" />
            <div class="preview-info">
              <span class="name">{{ product.name }}</span>
              <span class="quantity">x{{ product.SpSum }}</span>
            </div>
          </div>
        </div>

        <div class="footer">
          <div class="total-price">
            ￥{{ item.money.toFixed(2) }}
          </div>
          <div class="actions">
            <el-button type="primary" @click="handleEdit(item)">编辑</el-button>
            <el-button type="danger" @click="handleDelete(item.id)">删除</el-button>
          </div>
        </div>
      </div>
    </div>

    <el-pagination
      background
      layout="total, sizes, prev, pager, next"
      :total="total"
      v-model:current-page="currentPage"
      v-model:page-size="pageSize"
      @current-change="fetchData"
      @size-change="handleSizeChange"
      style="margin-top: 20px"
    />
<SetMenuDialog
  v-model="dialogVisible"
  :edit-data="currentEditData"
  @close="currentEditData = null,dialogVisible=false"
  @confirm="fetchData"
/>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import SetMenuDialog from '@/components/Product/SetMenuDialog.vue';
import {
  Get_Setmenu,
  Del_Setmenu,
  Get_Setmenu_product
} from '@/api/products/index';

// 在script部分添加加载状态


const searchKey = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const total = ref(0);
const tableData = ref<any[]>([]);
const loading = ref(false);
const dialogVisible = ref(false);
const currentEditData = ref<any>(null);

const fetchData = async () => {
  try {
    loading.value = true;
    const res = await Get_Setmenu({
      key: searchKey.value,
      page: currentPage.value,
      limit: pageSize.value
    });

    if (res.code === 0) {
      tableData.value = res.data.data;
      total.value = res.data.total;
    }
  } catch (error) {
    ElMessage.error('获取数据失败');
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (val: number) => {
  pageSize.value = val;
  fetchData();
};

const handleSearch = () => {
  currentPage.value = 1;
  fetchData();
};

// 修改handleCreate方法
const handleCreate = () => {
  currentEditData.value = null  // 明确设置为null触发重置
  dialogVisible.value = true
}



const handleEdit = async (row) => {
  try {
    const res = await Get_Setmenu_product({ id: row.id })
    if (res.code === 0) {
      currentEditData.value = {
        ...row,
        products: res.data.data.map(p => ({
          id: p.spSid,      // 修正字段映射
          SpPid: p.spPid,   // 保持组件需要的字段
          SpMoney: p.spMoney,
          SpSum: p.spSum,
          img:p.spImg
        }))
      }
      dialogVisible.value = true
    }
  } catch (error) {
    console.error(error)
    ElMessage.error('获取套餐详情失败')
  }
}



const handleDelete = (id: string) => {
  ElMessageBox.confirm('确认删除该套餐？', '警告', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(async () => {
    const res = await Del_Setmenu({ id });
    if (res.code === 0) {
      ElMessage.success('删除成功');
      fetchData();
    }
  }).catch(() => {});
  fetchData();
};


onMounted(() => {
  fetchData();
});
</script>



<style scoped>
.setmenu-container {
  padding: 20px;
}
.search-box {
  margin-bottom: 20px;
  background: #f5f7fa;
}
.el-table {
  border-radius: 8px;
  overflow: hidden;
}
.el-table::before {
  height: 0;
}
.el-pagination {
  justify-content: flex-end;
  margin-top: 20px;
}
.setmenu-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 24px;
  margin-top: 24px;
}

.setmenu-card {
  background: white;
  border-radius: 12px;
  padding: 20px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  transition: transform 0.3s ease;

  &:hover {
    transform: translateY(-5px);
  }
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;

  h3 {
    margin: 0;
    font-size: 16px;
    color: #333;
  }
}

.product-previews {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-bottom: 16px;
}

.preview-item {
  display: flex;
  align-items: center;
  background: #f8fafc;
  border-radius: 6px;
  padding: 8px;

  img {
    width: 40px;
    height: 40px;
    border-radius: 4px;
    margin-right: 8px;
  }

  .preview-info {
    display: flex;
    flex-direction: column;

    .name {
      font-size: 12px;
      @include text-ellipsis;
    }

    .quantity {
      font-size: 12px;
      color: #666;
    }
  }
}

.footer {
  display: flex;
  justify-content: space-between;
  align-items: center;

  .total-price {
    color: #f56c6c;
    font-weight: bold;
    font-size: 18px;
  }

  .actions {
    display: flex;
    gap: 8px;
  }
}
</style>
